PROJECT	= target

TARGET		= $(PROJECT).mot
COFF		= $(PROJECT).coff
MAPFILE		= $(PROJECT).map

SRC		= main.c
SRC		+= vs-wrc003.c
ASRC		= crt0.s
LDS		= 36064_rom.lds

ARCH		= h8300
CPU		= 36064

prefix		= h8300-hms-
CC		= $(prefix)gcc
AR		= $(prefix)ar
LD		= $(prefix)ld
OBJCOPY		= $(prefix)objcopy
OBJDUMP		= $(prefix)objdump

RM		= rm -f
REMOVEDIR	= rm -rf

INCLUDES	= -I. -I../include/
CFLAGS		= -mh -mrelax -mint32 -O2 $(INCLUDES)
CFLAGS		+= -nostdlib
CFLAGS		+= -Wall
ASFLAGS		= 
LIBS		= -lm -lc -lgcc
LDFLAGS		= -Xlinker -Map -Xlinker $(MAPFILE)

OBJDIR		= obj
OBJ		= $(ASRC:%.S=$(OBJDIR)/%.o) $(SRC:%.c=$(OBJDIR)/%.o)


.PHONY: all
all: obj_dir $(TARGET)


$(TARGET): $(COFF)
	$(OBJCOPY) -O srec $^ $@
#	$(OBJDUMP) -h $(COFF)


$(COFF) : $(OBJ) $(LDS)
	$(CC) $(CFLAGS) -T $(LDS) $(OBJ) -o $@ $(LIBS) $(LDFLAGS)


$(OBJDIR)/%.o : %.c
	$(CC) -c $(CFLAGS) -MD -MF $(OBJDIR)/$*.d $< -o $@

$(OBJDIR)/%.o : %.s
	$(CC) -c $(ASFLAGS) $< -o $@

$(OBJDIR)/%.s : %.c
	$(CC) -S $(CFLAGS) $< -o $@


obj_dir:
	$(shell mkdir $(OBJDIR) 2>/dev/null)



.PHONY: asm
asm: $(SRC:%.c=$(OBJDIR)/%.S)


.PHONY: writer
writer: $(TARGET)
	h8write.exe -3052 $^ /dev/ttyS3


.PHONY: clean
clean:
	$(RM) $(TARGET)
	$(RM) $(COFF)
	$(RM) $(MAPFILE)
	$(REMOVEDIR) $(OBJDIR)
	$(REMOVEDIR) $(DBG_DIR)






####################################
# Debug (using loader)             #
####################################

DBG_DIR		= dbg
DBG_TARGET	= $(DBG_DIR)/$(TARGET)
DBG_COFF	= $(DBG_DIR)/$(COFF)
DBG_MAPFILE	= $(DBG_DIR)/$(MAPFILE)

DBG_LDS	= 3052_dbg.lds

DBG_OBJ	= $(ASRC:%.S=$(DBG_DIR)/%.o) $(SRC:%.c=$(DBG_DIR)/%.o)

DBG_CFLAGS	= $(CFLAGS) -DLOADER
DBG_LDFLAGS	= -Xlinker -Map -Xlinker $(DBG_MAPFILE)


.PHONY: dbg
dbg: dbg_dir $(DBG_TARGET)

$(DBG_TARGET): $(DBG_COFF)
	$(OBJCOPY) -O srec $^ $@
	$(OBJDUMP) -h $(DBG_COFF)


$(DBG_COFF) : $(DBG_OBJ) $(DBG_LDS)
	$(CC) $(DBG_CFLAGS) -T $(DBG_LDS) $(DBG_OBJ) -o $@ $(LIBS) $(DBG_LDFLAGS)


$(DBG_DIR)/%.o : %.c
	$(CC) -c $(DBG_CFLAGS) -MD -MF $(DBG_DIR)/$*.d  $< -o $@

$(DBG_DIR)/%.o : %.S
	$(CC) -c $(ASFLAGS) $< -o $@


dbg_dir:
	$(shell mkdir $(DBG_DIR) 2>/dev/null)



-include $(OBJDIR)/*.d
-include $(DBG_DIR)/*.d

